# crud.py
from sqlmodel import select
from sqlalchemy.ext.asyncio import AsyncSession
from models import User
from schemas import UserCreate
from auth import hash_password

async def get_user_by_username(username: str, session: AsyncSession) -> User | None:
    """根据用户名获取用户"""
    statement = select(User).where(User.username == username)
    result = await session.execute(statement)
    return result.scalar_one_or_none()

async def create_user(user_in: UserCreate, session: AsyncSession) -> User:
    """创建新用户"""
    hashed_password = hash_password(user_in.password)
    # 创建用户对象但不包括密码字段
    db_user = User(
        username=user_in.username,
        full_name=user_in.full_name,
        hashed_password=hashed_password
    )
    session.add(db_user)
    await session.commit()
    await session.refresh(db_user)
    return db_user